package utils;


/**
 * 版本比较
 * Created by gongenbo on 2017/6/4.
 */
public class VerionCompare {
    /**
     * 版本阶段
     */
    private static String[] verPhase={"base","alpha","beta","rc","release"};
    /**
     * 版本比较函数
     * @param v1
     * @param v2
     * @return v1>v2=>+ v1<v2=>- v1=v2=>0
     * @throws Exception
     */
    public static int versionCompare(String v1,String v2) throws Exception {
        if(v1==null||v2==null){
            throw new Exception("version str is null");
        }
        if(v1.equals(v2)){
            return 0;
        }
        String[] arrV1=v1.split("\\.*_*-*");
        String[] arrV2=v2.split("\\.");
        int idx = 0;
        int minLength = Math.min(arrV1.length, arrV1.length);//取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = arrV1[idx].length() - arrV2[idx].length()) == 0//先比较长度
                && (diff = arrV1[idx].compareTo(arrV2[idx])) == 0) {//再比较字符
            ++idx;
        }
        //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : arrV1.length - arrV2.length;
        return diff;
    }
    public static void main(String[] args){
        //1.1.1.20170604_beta
        String v1="1.1.1.20170604_beta";
        String v2="1.1.1.20170605_beta";
        try {
            int ret = versionCompare(v1, v2);
            System.out.println(ret);
        }catch(Exception e){
            e.printStackTrace();
        }
        String[] arrV1=v1.split("\\.*_*-*");
        System.out.println("v1 len:"+v1.length());
    }
}

